﻿using System;
using System.Collections.Generic;
using System.Reflection;
using Autofac;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using ZilLion.Core.Unities.UnitiesMethods;
using ZilLion.Service.Core.Ioc;
using ZilLion.Service.WeChatMall.Domain.Repositorys.Interface;
using ZilLion.Service.WeChatMall.Domain.Responses.CrmProxy;
using ZilLion.Service.WeChatMall.Domain.Services.Interface;

namespace ZilLion.Service.WeChatMall.Controllers
{
    public class ComponentLoader : ComponentLoaderBase, IComponentLoader
    {
        public override Dictionary<string, string> InterceptJwtpayload(Dictionary<string, string> formpayload
          )
        {
            // TODO  || !formpayload.ContainsKey("selltype") 商城种类, 积分还是正常
            if (!formpayload.ContainsKey("appid") || !formpayload.ContainsKey("openid") ||
                !formpayload.ContainsKey("selltype")) return null;
            var result = new Dictionary<string, string>();
            var openid = formpayload["openid"];
            var appid = formpayload["appid"];
            var selltype = formpayload["selltype"];

            var appservice = IocContainer.Resolve<IAppInfoService>();
            var appinfo = appservice.GetAppByAppId(appid);
            if (appinfo == null)
                return null;
            var weChatMallCustReponsitory = IocContainer.Resolve<ICustReponsitory>();
            var entity = weChatMallCustReponsitory.GetCustEntity(appid, openid) ??
                         weChatMallCustReponsitory.AddCust(appid, openid);
            var response = HttpHelper.HttpRequestGet<AccessTokenResponse>(
                $"http://123.57.226.114:8061/Api/Component/GetAuthorization_info?Authorization_appid={appid}");
            result.Add("openid", openid);
            result.Add("wechataccesstoken", response?.authorizer_access_token ?? string.Empty);
            result.Add("appid", appid);
            result.Add("crmapigetway", appinfo.AppBasicInfo.CrmApiGetWay);
            result.Add("custid", entity?.CustId.ToString() ?? string.Empty);
            result.Add("selltype", selltype);
            return result;
        }

        public override void Register(ContainerBuilder builder)
        {
            base.Register(builder);
            RegisterAssemblis(Assembly.Load("ZilLion.Service.WeChatMall.Domain"));
        }

        
    }
}